home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / CPTUTT22.ZIP / CHAP01.TXT next >
Text File  |  1992-01-20  |  23KB  |  531 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.                                Chapter 1
  8.                            SIMPLE THINGS
  9.  
  10.  
  11. As we begin the study of C++ and object oriented programming, a few
  12. comments are in order to help you get started.  Since the field of
  13. object oriented programming is probably new to you, you will find
  14. that there is a significant amount of new terminology for you to
  15. grasp.  This is true of any new endeavor and you should be warned
  16. not to be intimidated by all of the new concepts.  We will add a
  17. few new topics in each chapter and you will slowly grasp the entire
  18. language.
  19.  
  20. Chapters one through four of this tutorial will concentrate on the
  21. non object oriented programming additions to C++.  We will not
  22. begin the discussion of any object oriented programming techniques
  23. until chapter five.
  24.  
  25.  
  26.  
  27. EVEN COMMENTS ARE IMPROVED IN C++
  28. _________________________________________________________________
  29.  
  30. Examine the file named CONCOM.CPP for an example   ==============
  31. of several new things in C++.  We will take the      CONCOM.CPP
  32. new constructs one at a time beginning with the    ==============
  33. comments.
  34.  
  35. A comment begins with the double slash "//", starts anywhere on a
  36. line, and runs to the end of that line where it is automatically
  37. terminated.  The old method of comment definition used with ANSI-
  38. C can also be used with C++ as illustrated in lines 11 through 14,
  39. among other places in this program.  The new method is the
  40. preferred method of comment definition because it is impossible to
  41. inadvertently comment out several lines of code.  This can be done
  42. by forgetting to include the end of comment notation when using the
  43. older C method of comment notation.  Good programming practice
  44. would be to use the new method for all comments and reserve the old
  45. method for use in commenting out a section of code during debugging
  46. since the two methods can be nested.
  47.  
  48. It would be well to caution you at this point however, that you
  49. should not use comments when the same sense of program definition
  50. can be obtained by using meaningful names for variables, constants,
  51. and functions.  The careful selection of variable and function
  52. names can make nearly any code self documenting and you should
  53. strive to achieve this in your code.
  54.  
  55.  
  56.  
  57.  
  58.                              Page 1-1
  59.  
  60.                     Chapter 1 - Simple Things
  61.  
  62. THE KEYWORDS const AND volatile
  63. _________________________________________________________________
  64.  
  65. There are two new keywords used in lines 9 through 11 which were
  66. not part of the original K&R definition of C, but are part of the
  67. ANSI-C standard.  The keyword const is used to define a constant.
  68. In line 9 the constant is of type int, it is named START, and is
  69. initialized to the value 3.  The compiler will not allow you to
  70. accidentally or purposefully change the value of START because it
  71. has been declared a constant.  If you had another variable named
  72. STARTS, the system would not allow you to slightly misspell STARTS
  73. as START and accidentally change it.  The compiler would give you
  74. an error message so you could fix the error.  Since it is not
  75. permissible to change the value of a constant, it is imperative
  76. that you initialize it when it is declared so it will have a useful
  77. value.  The compiler does not require you to initialize it however,
  78. and will not issue an error message if you do not.
  79.  
  80. You will note that the keyword const is also used in the function
  81. header in line 21 to indicate that the formal parameter named
  82. data_value is a constant throughout the function.  Any attempt to
  83. assign a new value to this variable will result in a compile error.
  84. This is a small thing you can add to your programs to improve the
  85. compilers ability to detect errors for you.
  86.  
  87. The keyword volatile is also part of the ANSI-C standard but was
  88. not included in the original K&R definition of C.  Even though the
  89. value of a volatile variable can be changed by you, the programmer,
  90. there may be another mechanism by which the value could be changed,
  91. such as by an interrupt timer causing the value to be incremented.
  92. The compiler needs to know that this value may be changed by some
  93. external force when it optimizes the code.  A study of code
  94. optimization methods is very interesting, but beyond the scope of
  95. this tutorial.  Note that a constant can also be volatile, which
  96. means that you cannot change it, but the system can through some
  97. hardware function.
  98.  
  99. Ignore the output statement given in line 23 for a few minutes.
  100. We will study it in some detail later in this chapter.  If you are
  101. experienced in K&R style programming, you may find line 5 and 21
  102. a little strange.  This illustrates prototyping and the modern
  103. method of function definition as defined by the ANSI-C standard.
  104. We will discuss this in great detail in chapter 4 of this tutorial.
  105. Prototyping is optional in C but absolutely required in C++.  For
  106. that reason, chapter 4 of this tutorial is devoted entirely to
  107. prototyping.
  108.  
  109. It would be advantageous for you to compile and execute this
  110. program with your C++ compiler to see if you get the same result
  111. as given in the comments at the end of the listing.  One of the
  112. primary purposes of compiling it is to prove that your compiler is
  113. loaded and executing properly.
  114.  
  115.  
  116.  
  117.                              Page 1-2
  118.  
  119.                     Chapter 1 - Simple Things
  120.  
  121. THE SCOPE OPERATOR
  122. _________________________________________________________________
  123.  
  124. The example program named SCOPEOP.CPP             ===============
  125. illustrates another construct that is new to        SCOPEOP.CPP
  126. C++.  There is no corresponding construct in      ===============
  127. either K&R or ANSI-C.  This allows access to the
  128. global variable named index even though there is
  129. a local variable of the same name within the main function.  The
  130. use of the double colon in front of the variable name, in lines 11,
  131. 13, and 16, instructs the system that we are interested in using
  132. the global variable named index, defined in line 4, rather than the
  133. local variable defined in line 8.
  134.  
  135. The use of this technique allows access to the global variable for
  136. any use.  It could be used in calculations, as a function
  137. parameter, or for any other purpose.  It is not really good
  138. programming practice to abuse this construct, because it could make
  139. the code difficult to read.  It would be best to use a different
  140. variable name instead of reusing this name, but the construct is
  141. available to you if you find that you need it sometime.
  142.  
  143. The scope operator allows access to global variables even though
  144. hidden by a local variable.  Be sure to compile and execute this
  145. program before proceeding on to the next example program where we
  146. will discuss the cout operator in lines 10, 11, 15, and 16.
  147.  
  148.  
  149. THE iostream LIBRARY
  150. _________________________________________________________________
  151.  
  152. Examine the example program named MESSAGE.CPP     ===============
  153. for our first hint of object oriented               MESSAGE.CPP
  154. programming, even though it is a very simple      ===============
  155. one.  In this program, we define a few variables
  156. and assign values to them for use in the output
  157. statements illustrated in lines 17 through 20, and in lines 23
  158. through 26.  The new operator cout is the output function to the
  159. standard device, the monitor, but works a little differently from
  160. our old familiar printf() function, because we do not have to tell
  161. the system what type we are outputting.
  162.  
  163. C++, like the C language itself, has no input or output operations
  164. as part of the language itself, but defines the stream library to
  165. add input and output functions in a very elegant manner.
  166.  
  167. The operator <<, sometimes called the "put to" operator but more
  168. properly called the insertion operator, tells the system to output
  169. the variable or constant following it, but lets the system decide
  170. how to output the data.  In line 17, we first tell the system to
  171. output the string, which it does by copying characters to the
  172. monitor, then we tell it to output the value of index.  Notice
  173. however, that we fail to tell it what the type is or how to output
  174. the value.  Since we don't tell the system what the type is, it is
  175.  
  176.                              Page 1-3
  177.  
  178.                     Chapter 1 - Simple Things
  179.  
  180. up to the system to determine what the type is and to output the
  181. value accordingly.  After the system finds the correct type, we
  182. also leave it up to the system to use the built in default as to
  183. how many characters should be used for this output.  In this case,
  184. we find that the system uses exactly as many as needed to output
  185. the data, with no leading or trailing blanks, which is fine for
  186. this output.  Finally, the newline character is output, and the
  187. line of code is terminated with a semicolon.
  188.  
  189. When we called the cout output function in line 17, we actually
  190. called two different functions because we used it to output a
  191. string and a variable of type int.  This is the first hint at
  192. object oriented programming because we simply broadcast a message
  193. to the system to print out a value, and let the system find an
  194. appropriate function to do so.  We are not required to tell the
  195. system exactly how to output the data, we only tell it to output
  196. it.  This is a very weak example of object oriented programming,
  197. and we will get into it in much more depth later.
  198.  
  199. In line 18, we tell the system to output a different string,
  200. followed by a floating point number, and another string of one
  201. character, the newline character.  In this case, we told it to
  202. output a floating point number without telling it that it was a
  203. floating point number, once again letting the system choose the
  204. appropriate output means based on its type.  We did lose a bit of
  205. control in the transaction, however, because we had no control over
  206. how many significant digits to print before or after the decimal
  207. point.  We chose to let the system decide how to format the output
  208. data.
  209.  
  210. The variable named letter is of type char, and is assigned the
  211. value of the uppercase X in line 14, then printed as a letter in
  212. line 19.
  213.  
  214. Because C++ has several other operators and functions available
  215. with streams, you have complete flexibility in the use of the
  216. stream output functions.  You should refer to your compiler
  217. documentation for details of other available formatting commands.
  218. The cout and the printf() statements can be mixed in any way you
  219. desire.  Both statements result in output to the monitor.
  220.  
  221.  
  222. MORE ABOUT THE stream LIBRARY
  223. _________________________________________________________________
  224.  
  225. The stream library was defined for use with C++ in order to add to
  226. the execution efficiency of the language.  The printf() function
  227. was developed early in the life of the C language and is meant to
  228. be all things to all programmers.  As a result, it became a huge
  229. function with lots of extra baggage that is only used by a few
  230. programmers.  By defining the small special purpose stream library,
  231. the designer of C++ allows the programmer to use somewhat limited
  232. formatting capabilities, which are still adequate for most
  233. programming jobs.  If more elaborate formatting capabilities are
  234.  
  235.                              Page 1-4
  236.  
  237.                     Chapter 1 - Simple Things
  238.  
  239. required, the complete printf() library is available within any C++
  240. program, and the two types of outputs can be freely mixed.
  241.  
  242. Lines 23 through 26 illustrate some of the additional features of
  243. the stream library which can be used to output data in a very
  244. flexible yet controlled format.  The value of index is printed out
  245. in decimal, octal, and hexadecimal format in lines 23 through 25.
  246. When one of the special stream operators, dec, oct, or hex, is
  247. output, all successive output will be in that number base.  Looking
  248. ahead to line 32, we find the value of index printed in hex format
  249. due to the selection of the hexadecimal base in line 25.  If none
  250. of these special stream operators are output, the system defaults
  251. to decimal format.
  252.  
  253.  
  254. THE cin OPERATOR
  255. _________________________________________________________________
  256.  
  257. In addition to the cout operator, there is a cin operator which is
  258. used to read data from the standard input device, usually the
  259. keyboard.  The cin operator uses the >> operator, usually called
  260. the "get from" operator but properly called the extraction
  261. operator.  It has most of the flexibility of the cout operator.
  262. A brief example of the use of the cin operator is given in lines
  263. 28 through 30.  The special stream operators, dec, oct, and hex,
  264. also select the number base for the cin stream separately from the
  265. cout stream.  If none is specified, the input stream also defaults
  266. to decimal.
  267.  
  268. In addition to the cout operator and the cin operator there is one
  269. more standard operator, the cerr, which is used to output to the
  270. error handling device.  This device cannot be redirected to a file
  271. like the output to the cout can be.  The three operators, cout,
  272. cin, and cerr, correspond to the stdout, the stdin, and the stderr
  273. stream pointers of the programming language C.  Their use will be
  274. illustrated throughout the remainder of this tutorial.
  275.  
  276. The stream library also has file I/O capability which will be
  277. briefly illustrated in the next example program.
  278.  
  279. Be sure to compile and execute this program before going on to the
  280. next one.  Remember that the system will ask you to enter an
  281. integer value which will be echoed back to the monitor, but changed
  282. to the hexadecimal base.
  283.  
  284.  
  285. FILE STREAM OPERATIONS
  286. _________________________________________________________________
  287.  
  288. Examine the example program named FSTREAM.CPP     ===============
  289. for examples of the use of streams with files.      FSTREAM.CPP
  290.                           ===============
  291. In this program a file is opened for reading,
  292. another for writing, and a third stream is
  293.  
  294.                              Page 1-5
  295.  
  296.                     Chapter 1 - Simple Things
  297.  
  298. opened to the printer to illustrate the semantics of stream
  299. operations on a file.  The only difference between the streams in
  300. the last program and the streams in this program is the fact that
  301. in the last program, the streams were already opened for us by the
  302. system.  You will note that the stream named printer is used in the
  303. same way we used the cout operator in the last program.  Finally,
  304. because we wish to exercise good programming practice, we close
  305. all of the files we have opened prior to ending the program.
  306.  
  307. The standard file I/O library is available with ANSI-C and is as
  308. easy to use as the stream library and very portable.  For more
  309. information on the stream file I/O library, see Bjarne Stroustrup's
  310. book which is listed in the introduction to this tutorial, or refer
  311. to your compiler documentation.
  312.  
  313. Be sure to compile and execute this program.  When you execute it,
  314. it will request a file to be copied.  You can enter the name of any
  315. ASCII file that resides in the current directory.
  316.  
  317.  
  318. VARIABLE DEFINITIONS
  319. _________________________________________________________________
  320.  
  321. Examine the file named VARDEF.CPP for a few more   ==============
  322. additions to the C++ language which aid in           VARDEF.CPP
  323. writing a clear and easy to understand program.    ==============
  324. In C++, as in ANSI-C, global and static
  325. variables are automatically initialized to zero
  326. when they are declared.  The variables named index in line 4, and
  327. goofy in line 26 are therefore automatically initialized to zero.
  328. Of course, you can still initialize either to some other value if
  329. you so desire.  Global variables are sometimes called external
  330. since they are external to any functions.
  331.  
  332. Automatic variables, those declared inside of any function, are not
  333. automatically initialized but will contain the value that happens
  334. to be in the location where they are defined, which must be
  335. considered a garbage value.  The variable named stuff in line 8,
  336. therefore does not contain a valid value, but some garbage value
  337. which should not be used for any meaningful purpose.  In line 11,
  338. it is assigned a value based on the initialized value of index and
  339. it is then displayed on the monitor for your examination.
  340.  
  341.  
  342. THE REFERENCE VARIABLE
  343. _________________________________________________________________
  344.  
  345. Notice the ampersand in line 9.  This defines another_stuff as a
  346. reference variable which is a new addition to C++.  The reference
  347. variable should not be used very often, if at all, in this context.
  348. In order to be complete however, we will discuss its operation.
  349. The reference variable is not quite the same as any other variable
  350. because it operates like a self dereferencing pointer.  Following
  351. its initialization, the reference variable becomes a synonym for
  352.  
  353.                              Page 1-6
  354.  
  355.                     Chapter 1 - Simple Things
  356.  
  357. the variable stuff, and changing the value of stuff will change the
  358. value of another_stuff because they are both actually referring to
  359. the same variable.  The synonym can be used to access the value of
  360. the variable for any legal purpose in the language.  It should be
  361. pointed out that a reference variable must be initialized to
  362. reference some other variable when it is declared or the compiler
  363. will respond with an error.  Following initialization, the
  364. reference variable cannot be changed to refer to a different
  365. variable.
  366.  
  367. The use of the reference variable in this way can lead to very
  368. confusing code, but it has another use where it can make the code
  369. very clear and easy to understand.  We will study this use in
  370. chapter 4 of this tutorial.
  371.  
  372.  
  373.  
  374. DEFINITIONS ARE EXECUTABLE STATEMENTS
  375. _________________________________________________________________
  376.  
  377. Coming from your background of C, you will find the statement in
  378. line 16 very strange, but this is legal in C++.  Anyplace it is
  379. legal to put an executable statement, it is also legal to declare
  380. a new variable because a data declaration is defined as an
  381. executable statement in C++.  In this case, we define the new
  382. variable named more_stuff and initialize it to the value of 13.
  383. It has a scope from the point where it was defined to the end of
  384. the block in which it is defined, so it is valid throughout the
  385. remainder of the main program.  The variable named goofy is
  386. declared even later in line 26.
  387.  
  388. It is very significant that the variable is declared near its point
  389. of usage.  This makes it easier to see just what the variable is
  390. used for, since it has a much more restricted scope of validity.
  391. When you are debugging a program, it is convenient if the variable
  392. declaration is located in close proximity to where you are
  393. debugging the code.
  394.  
  395.  
  396.  
  397. WHAT ABOUT definition AND declaration?
  398. _________________________________________________________________
  399.  
  400. The words definition and declaration refer to two different things
  401. in C++, and in ANSI-C also for that matter.  They really are
  402. different and have different meanings, so we should spend a little
  403. time defining exactly what the words mean in C++.  A declaration
  404. provides information to the compiler about the characteristics of
  405. something such as a type or a function but it doesn't actually
  406. define any code to be used in the executable program, and you are
  407. permitted to make as many declarations of the same entity as you
  408. desire.  A definition, on the other hand, actually defines
  409. something that will exist in the executable program, either some
  410. useful variables, or some executable code, and you are required to
  411.  
  412.                              Page 1-7
  413.  
  414.                     Chapter 1 - Simple Things
  415.  
  416. have one and only one definition of each entity in the program.
  417. In short, a declaration introduces a name into the program and a
  418. definition introduces some code.
  419.  
  420. If we declare a struct, we are only declaring a pattern to tell the
  421. compiler how to store data later when we define one or more
  422. variables of that type.  But when we define some variables of that
  423. type, we are actually declaring their names for use by the
  424. compiler, and defining a storage location to store the values of
  425. the variables.  Therefore, when we define a variable, we are
  426. actually declaring it and defining it at the same time.
  427.  
  428. We will refer to these definitions many times throughout the course
  429. of this tutorial so if this is not clear now, it will clear up
  430. later.
  431.  
  432.  
  433. A BETTER for LOOP
  434. _________________________________________________________________
  435.  
  436. Take careful notice of the for loop defined in line 20.  This loop
  437. is a little clearer than the for loop that is available in ANSI-
  438. C, because the loop index is defined in the for loop itself.  The
  439. scope of this loop index is from its declaration to the end of the
  440. enclosing block.  In this case its scope extends to line 29 since
  441. the closing brace in line 29 corresponds to the most recent opening
  442. brace prior to the declaration of the variable.  Since the variable
  443. is still available, it can be used for another loop index or for
  444. any other purpose which an integer type variable can legally be
  445. used for.  The variable named count2 is declared and initialized
  446. during each pass through the loop because it is declared within the
  447. block controlled by the for loop.  Its scope is only the extent of
  448. the loop so that it is automatically deallocated each time the loop
  449. is completed.  It is therefore declared, initialized, used and
  450. deallocated five times, once for each pass through the loop.
  451.  
  452. You will notice that the variable count2 is assigned a numerical
  453. value in line 22 but when it is printed out, a character value is
  454. actually output.  This is because C++ (version 2.0 and later) is
  455. careful to use the correct type.
  456.  
  457. Finally, as mentioned earlier, the static variable named goofy is
  458. declared and automatically initialized to zero in line 26.  Its
  459. scope is from the point of its declaration to the end of the block
  460. in which it is declared, line 29.
  461.  
  462. Be sure to compile and execute this program.
  463.  
  464.  
  465. OPERATOR PRECEDENCE
  466. _________________________________________________________________
  467.  
  468. Operator precedence is identical to that defined for ANSI-C so no
  469. attempt will be made here to define it.  There is a small
  470.  
  471.                              Page 1-8
  472.  
  473.                     Chapter 1 - Simple Things
  474.  
  475. difference when some operators are overloaded which we will learn
  476. to do later in this tutorial.  Some of the operators act slightly
  477. different when overloaded than the way they operate with elements
  478. of the predefined language.
  479.  
  480. Do not worry about the previous paragraph, it will make sense later
  481. in this tutorial after we have studied a few more topics.
  482.  
  483.  
  484. PROGRAMMING EXERCISES
  485. _________________________________________________________________
  486.  
  487.  
  488. 1.   Write a program that displays your name and date of birth on
  489.      the monitor three times using the cout function.  Define any
  490.      variables you use as near as possible to their point of usage.
  491.  
  492. 2.   Write a program with a few const values and volatile variables
  493.      and attempt to change the value of the constants to see what
  494.      kind of error message your compiler will give you.
  495.  
  496. 3.   Write a program that uses streams to interactively read in
  497.      your birthday with three different cin statements.  Print your
  498.      birthday in octal, decimal, and hexadecimal notation just for
  499.      the practice.
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.                              Page 1-9
  531.